package com.kuang.config;

import com.kuang.pojo.User;
import com.kuang.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @program: springboot07shiro
 * @description:
 * @author: 陈恩涛
 * @create: 2020-10-29 21:53
 **/

//自定义的Realm:UserRealm   extends AuthorizingRealm
public class UserRealm extends AuthorizingRealm {

    @Autowired
    UserService userService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了授权：doGetAuthorizationInfo");

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        //info.addStringPermission("user:add");

        //拿到当前登录的这个对象
        Subject subject = SecurityUtils.getSubject();

        //获取在认证中SimpleAuthenticationInfo构造的第一个参数,拿到User对象
        User currentUser = (User) subject.getPrincipal();

        //设置当前用户的权限
        info.addStringPermission(currentUser.getPerms());

//        return null;
        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了认证：doGetAuthenticationInfo");

        //用户名，密码~   数据库中取

        UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;

        User user = userService.queryUserByName(userToken.getUsername());

        if(user==null){ //不存在这个用户
            return null;    //抛出异常  UnknownAccountException
        }

        //可以加密： MD5加密，   MD5盐值加密
        //密码认证，shiro做~
        ByteSource credentialSalt = ByteSource.Util.bytes(userToken.getUsername());

        //第一个参数用于传值，第二个参数为数据库中加密了的密码，第三个参数为盐值，第四个参数为Realm name
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user, user.getPwd(), credentialSalt, getName());

        return authenticationInfo;


        //return new SimpleAuthenticationInfo("",user.getPwd(),"");


    }


}
